
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import api from '@/api/api'
import axios from 'axios'
import Vue from 'vue'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      api.login({ userName: username.trim(), userPass: password }).then(response => {
        const { code, data, msg } = response
        if (code === 0) {
          axios.defaults.headers.common['token'] = data.token
          commit('SET_TOKEN', data.token)
          setToken(data.token)
        } else {
          Vue.prototype.$message.error(msg)
        }
        resolve()
      }).catch(error => {
        reject(error)
        console.log(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise(resolve => {
      commit('SET_ROLES', 'admin')
      commit('SET_NAME', 'admin')
      // commit('SET_AVATAR', avatar)
    })
  },

  // user logout
  logout({ commit, state }) {
    removeToken() // must remove  token  first
    resetRouter()
    commit('SET_ROLES', []);
    commit('RESET_STATE')
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

